package com.jiuqi.captcha.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

public class CaptchaUtil {

    private static DefaultKaptcha kaptcha;

    static {
        Properties properties = new Properties();
        // 配置验证码生成器
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "200");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        Config config = new Config(properties);
        kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(config);
    }

    // 生成验证码图片并返回图片数据
    public static byte[] generateCaptchaImage(HttpSession session) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 生成验证码字符串
        String captchaText = kaptcha.createText();
        // 打印验证码字符串
        System.out.println("Generated Captcha Text: " + captchaText);
        // 将验证码字符串存储到 session 中，用于后续验证
        session.setAttribute("captchaText", captchaText);
        // 生成验证码图片
        BufferedImage image = kaptcha.createImage(captchaText);
        // 将图片写入字节流
        ImageIO.write(image, "jpg", outputStream);
        // 获取图片字节数据
        byte[] captchaBytes = outputStream.toByteArray();
        outputStream.close();
        return captchaBytes;
    }
}

